package ZengJiHong2.Test4;

import java.util.Arrays;
import java.util.Objects;

/**
 * @ClassName myArrayList
 * @Author 16799
 * @Date 2025/8/20 10:03
 * @Version 1.0
 * @Description TODO
 **/
public class myArrayList<E> {
    private Object[] elementdata = {};
    private int size;
    private int default_capacity = 10;

    public boolean add(E e){
        //第一次是两个都是0，需要初始化。第二次就是两个都是10
        if (size == elementdata.length){
            grow();
        }
        elementdata[size++] = e;
        return true;
    }

    public E get(int index){
        checkIndex(index);

        return (E) elementdata[index];
    }

    public E remove (int index){
        checkIndex(index);
        //返回被删除的元素
        E e = (E) elementdata[index];

        //删除index索引处元素后，需要移位元素的个数
        //[0,0,0,0,0, ]
        // 0,1,2,3,4,5   size=5
        int moveFlag = size-index-1;
        if (moveFlag!=0){
            //方法一，用arraycopy方法
            //System.arraycopy(elementdata,index+1,elementdata,index,moveFlag);

            //方法二，自己写个算法：验证过，效果一样
            for (int i = index; i < size; i++) {
                elementdata[i] = elementdata[i+1];
            }

        }

        //把原数组的最后一位改为null
        elementdata[--size] = null;
        return e;
    }

    public void foreach(myConsumer<E> action){
        Objects.requireNonNull(action);
        for (int i = 0; i < size; i++) {
            action.accept((E) elementdata[i]);
        }
    }

    public void checkIndex(int index) {
        if (index<0||index>=size){
            throw new IndexOutOfBoundsException("越界了你个傻逼");
        }
    }

    private void grow() {
        if (size==0){
            elementdata = new Object[default_capacity];
        }else {
            //不是第一次，那就需要扩容1.5倍
            elementdata = Arrays.copyOf(elementdata, elementdata.length+(elementdata.length>>1));
        }
    }

    public int size(){
        return size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            E e = (E) elementdata[i];
            sb.append(e).append(i==size-1? "":",");
        }
        sb.append("]");
        return sb.toString();
    }
}
